// import {env} from '@/config/env'
// const apiUrl = __wxConfig.envVersion == 'develop'||__wxConfig.envVersion == 'trial'?"mpro23.ywhzsoft.com/netWf2024UnitiveTest/":"mpro23.ywhzsoft.com/netWf2024Unitive/";

const apiUrl = uni.getStorageSync('baseUrl') ? uni.getStorageSync('baseUrl')+'/' : ""

import Base64 from "../utils/base.js";
let base64 = new Base64()

// import {
// 	jwtDecode
// } from 'jwt-decode';

const reflushToken = function() {
	return new Promise((resolve, reject) => {
		uni.request({
			// url: `${apiUrl}/Auth/reflushToken.aspx`,
			url: `https://${apiUrl}/Auth/reflushToken.aspx`,
			header: {
				'Authorization': 'Bearer ' + uni.getStorageSync('token')
			},
			success: (r) => {
				//reject();
				// console.log(r)
				if(r.data.code == 1) {
					uni.setStorageSync('token', r.data.result.token)
					let splitToken = r.data.result.token.split('.')
					let info = splitToken[1].replace(/-/g, '+').replace(/_/g, '/')
					let jwt = base64.decode(info.toString())
					let arr = ((jwt.replace(/\{|}/g,'')).replace(/\"/g, "")).split(',')
					arr.some(val => {
						if(val.indexOf('movePrice') != -1) {
							let tempArr = val.split(':')
							uni.setStorageSync('movePrice',tempArr[1])
							return true
						}
					})
					// uni.setStorageSync('uid', r.data.result.uid)
					// uni.setStorageSync('password', r.data.result.password)
					uni.setStorageSync('loginUserName', r.data.result.loginUserName)
					
					resolve()
				} else {
					uni.showModal({
						title:'提示',
						content:r.data.message,
						showCancel:false,
						success: (r) => {
							if(r.confirm) {
								uni.reLaunch({
									url:'/pages/login/login'
								})
							}
						}
					})
					reject()
				}
			}
		})
	})
}

// console.log("jwtDecode1",jwtDecode)
//不校验token的接口
const ignoreURL= ['Auth/checkAccount.aspx', 'Auth/checkLogin.aspx']
// 请求拦截
// const userId = jwt_decode('2122')
const request = async (options) => {
	const systemInfo = uni.getSystemInfoSync();
	// console.log(options)
	// 显示加载中
	let token = uni.getStorageSync('token')

	// if(ignoreURL.indexOf(options.url) == -1)
	if(ignoreURL.indexOf(options.url) == -1 && systemInfo.platform === 'android')
	{

		let splitToken = token.split('.')
		let info = splitToken[1].replace(/-/g, '+').replace(/_/g, '/')
		let jwt = base64.decode(info.toString())
		let arr = ((jwt.replace(/\{|}/g,'')).replace(/\"/g, "")).split(',')
		let exp 
		arr.some(val => {
			if(val.indexOf('exp') != -1) {
				let tempArr = val.split(':')
				exp = new Date(tempArr[1] * 1000)
				return true
			}
		})
		if (new Date() >= exp) {
			await reflushToken();
			token = uni.getStorageSync('token')
		}
		// console.log(arr,'arr')
	}

	uni.showLoading({
		title: '加载中',
		mask: true
	})
	// decryptToken.decryptJWT()
	// 判断如果是post请求，就设置请求头
	if (options.method === 'POST') {
		options.header = Object.assign({
			'content-type': `application/x-www-form-urlencoded`
		}, options.header)

		// if (!!options.headerText) {
		// 	options.header = {
		// 		'content-type': "'" + options.headerText + "'",
		// 		'Authorization': 'Bearer ' + token
		// 	}
		// }
	}

	!!options.header || (options.header = {})
	options.header['Authorization'] = 'Bearer ' + token

	// 拼接url
	const apiUrl = uni.getStorageSync('baseUrl') ? uni.getStorageSync('baseUrl')+'/' : ""
	// options.url = 'https://' + apiUrl + options.url

	if (systemInfo.platform === 'android') {
		// 是H5端
		options.url = 'https://' + apiUrl + options.url
	} else {
		// 其他端
		options.url = '/api/' + options.url
	}

	console.log(' url ==' , options.url)
	return new Promise((resolve, reject) => {
		uni.request({
			...options,
			success: (res) => {

				console.log('== res request ', res)

				// 判断状态码
				if (res.statusCode !== 200) {
					setTimeout(() => {
						uni.hideLoading()
					}, 1500)
					uni.showToast({
						title: '网络请求失败',
						icon: 'none'
					})
					return reject(res)
				}

				if (res.data.code == '-101') {
					uni.hideLoading()
					
					uni.showModal({
						title: '提示',
						content: '登录信息已过期，是否退出登陆',
						success: function (res) {
							if (res.confirm) {
								uni.redirectTo({
									url: '/pages/login/login2'
								})
							}
						}
					});

					return reject(res.data)
				}
				// 判断业务状态码
				if (res.data.code !== 1) {
					setTimeout(() => {
						uni.hideLoading()
					}, 1500)
					uni.showToast({
						title: res.data.message,
						icon: 'none'
					})

					return reject(res.data)
				}
				// 成功
				uni.hideLoading()
				resolve(res.data.result)
				
			},
			fail: (err) => {
				console.log('== err request ', err)
				setTimeout(() => {
					uni.hideLoading()
				}, 1500)
				uni.showToast({
					title: '网络请求失败',
					icon: 'none'
				})
				
				setTimeout(() => {
					reject(err)
				}, 1500)
			},
			complete: () => {

			}
		})
	})
}

export default request